﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;
using SystemLYH.Domain.Dto;

namespace T.Contract.Api.Extensions
{
    public class ExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<ExceptionFilter> _logger;
        private static readonly string Hostname;
        private static readonly string IpAddress;

        static ExceptionFilter()
        {
            // 获取并缓存主机名和 IP 地址
            Hostname = Dns.GetHostName();
            var hostentry = Dns.GetHostEntry(Hostname);
            var ipaddress = hostentry.AddressList.FirstOrDefault(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
            IpAddress = ipaddress?.ToString() ?? "未知的IP";

        }
        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            _logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            //记录异常信息
            var exception = context.Exception;
            var exceptionMessage = exception.Message;
            var stackTrace = exception.StackTrace;
            //获取请求信息
            var requestPath = context.HttpContext.Request.Path;
            var requestMethod = context.HttpContext.Request.Method;

            //记录异常日志，并返回错误响应
            _logger.LogError("异常发生：\n" +
                $"主机名：{Hostname}\n" +
                $"IP地址：{IpAddress}\n" +
                $"请求路径：{requestPath}\n" +
                $"请求方法：{requestMethod}\n" +
                $"异常信息：{exceptionMessage}\n" +
                $"堆栈跟踪：{stackTrace?.Substring(0, 50)}");
            var errorResponse = new ApiResult<string>
            {
                Code = -1,
                Message = "服务器内部错误,请稍后再试",
            };
            context.Result = new JsonResult(errorResponse);

            //标记异常已处理，以免其他异常处理程序处理

            context.ExceptionHandled = true;
        }
    }
}
